"use strict";

const Controller = require("egg").Controller;

class PageController extends Controller {
  async index() {
    const { ctx, app } = this;

    const {
      current,
      size,
      title = "",
      path = "",
      status = "",
    } = ctx.request.body;

    let sql = " ";

    if (title) {
      sql += `where title = "${title}" `;
    } else if (path) {
      sql += `where path = "${path}" `;
    } else if (status) {
      sql += `where status = "${status}" `;
    }

    let limit = ` limit ${(current - 1) * size} , ${size}`;

    const data = await app.mysql.query(`select * from page ` + sql + limit);

    const total = (
      await app.mysql.query(`select count(*) as count from page` + sql)
    )[0].count;

    ctx.body = {
      code: 1,
      data,
      total,
    };
  }

  // 下线/发布
  async issue() {
    const { ctx, app } = this;

    const { id } = ctx.request.body;

    const { multipleSelection, status } = ctx.request.body;

    // 单个下线/发布
    if (id) {
      const data = await app.mysql.get("page", { id });

      if (data.status) {
        await app.mysql.update("page", { id, status: 0 });
      } else {
        await app.mysql.update("page", { id, status: 1 });
      }
    }
    // 批量下线/发布
    else {
      multipleSelection.forEach(async (item) => {
        await app.mysql.update("page", { id: item.id, status: status });
      });
    }

    ctx.body = {
      code: 1,
      msg: "操作成功",
    };
  }

  async del() {
    const { ctx, app } = this;

    const { id } = ctx.request.body;

    const multipleSelection = ctx.request.body;

    if (id) {
      await app.mysql.delete("page", { id });
    }

    if (multipleSelection.length) {
      multipleSelection.forEach(async (item) => {
        await app.mysql.delete("page", { id: item.id });
      });
    }

    ctx.body = {
      code: 1,
      msg: "删除成功",
    };
  }
}

module.exports = PageController;
